package com.ebupt.migu.music.effectStatistics.service.Impl;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ebupt.migu.music.common.entity.Page;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MiguRuntimeException;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.common.util.HttpUtils;
import com.ebupt.migu.music.effectStatistics.entity.SmsRequest;
import com.ebupt.migu.music.effectStatistics.entity.SmsResponse;
import com.ebupt.migu.music.effectStatistics.entity.StatisticsSms;
import com.ebupt.migu.music.effectStatistics.entity.vo.SMSDailyReportExportVo;
import com.ebupt.migu.music.effectStatistics.entity.vo.SmsExportVo;
import com.ebupt.migu.music.effectStatistics.mapper.SMSOperationMapper;
import com.ebupt.migu.music.effectStatistics.service.SMSOperationService;
import com.ebupt.migu.music.strategy.entity.StrategyInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author zhuar
 */
@Slf4j
@Service
public class SMSOperationServiceImpl implements SMSOperationService {
    @Autowired
    private SMSOperationMapper smsOperationMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${sms.accessCode}")
    private String accessCode;
    @Value("${sms.resultUrl}")
    private String resultUrl;
    /**
     * 分页查询
     * @param params
     * @return
     */
    @Override
    public ResultObject queryMap(Map<String, Object> params){
        ResultObject<Page<HashMap<String, Object>>> res = new ResultObject<>();
        // 是否系统管理员 1-系统管理员； 0-普通用户；
        String is_admin = params.get("isAdmin").toString();
        if ("1".equals(is_admin) || "1".equals(params.get("isSuperAdmin"))){//是否超级管理员
            params.remove("creatorDepartment");
        }
        // 判断是查询明细还是汇总
        String summary = params.get("summary").toString();
        // 查询总条数
        Integer total = "1".equals(summary) ? smsOperationMapper.countSummary(params) : smsOperationMapper.countQuery(params);
        // 分页查询结果集
        List<HashMap<String, Object>> datas = "1".equals(summary) ? smsOperationMapper.querySummary(params) : smsOperationMapper.queryMap(params);
        // 分页
        Page<HashMap<String, Object>> page = new Page<>();
        page.setTotal(total);
        page.setData(datas);
        res.setData(page);
        return res;
    }

    /**
     * 目标人群
     * @param params
     * @return
     */
    @Override
    public ResultObject targetUser(Map<String, Object> params) {
        ResultObject<List<HashMap<String, Object>>> res = new ResultObject<>();
        // 是否超级管理员 1-超级管理员； 0-普通用户；
        String is_admin = params.get("isAdmin").toString();
        if ("1".equals(is_admin)){
            params.remove("creatorDepartment");
        }
        //根据strategy_type策略类型判断调用哪个条件查询
        // 1-短信策略；2-banner策略；3-音乐之声策略；4-push策略
        List<HashMap<String, Object>> list = smsOperationMapper.targetUser(params);
        res.setMsg("success");
        res.setData(list);
        return res;
    }

    /**
     * 导出
     * @param params
     * @return
     */
    @Override
    public List<SmsExportVo> exportMap(Map<String, Object> params){
        // 是否超级管理员 1-超级管理员； 0-普通用户；
        String is_admin = params.get("isAdmin").toString();
        if ("1".equals(is_admin)){
            params.remove("creatorDepartment");
        }
        // 判断是查询明细还是汇总
        String summary = params.get("summary").toString();
        List<SmsExportVo> datas = "1".equals(summary) ? smsOperationMapper.exportSummary(params) : smsOperationMapper.exportMap(params);
        return datas;
    }

    @Override
    public void smsResultTask() {
        // 获取已推送但未获取效果统计的短信策略
        List<StatisticsSms> resultList = smsOperationMapper.selectList(new QueryWrapper<StatisticsSms>().lambda()
                .eq(StatisticsSms::getIsResultBack, 0));
        resultList.forEach(rl -> {
            long distanceTime = System.currentTimeMillis() -
                    Objects.requireNonNull(DateUtil.parseStrToDate(rl.getEndTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS)).getTime();
            long resultDuration = 24 * 60 * 60 * 1000;
            //短信24小时后去获取统计结果--只调一次
            if (distanceTime > resultDuration) {
                StrategyInfo strategyInfo = smsOperationMapper.qryByStrategyId(rl.getStrategyId());
                Optional.ofNullable(strategyInfo).ifPresent(e -> {
                    SmsResponse sr = remotePost(rl.getStrategyId(),rl.getDate());
                    Optional.ofNullable(sr).ifPresent(s -> {
                        // 设置更新参数
                        String iopKey = rl.getStrategyId() + "_" + rl.getDate() + "_iop";
                        Integer iop = redisTemplate.hasKey(iopKey) ? Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get(iopKey)).toString()) : 0;
                        rl.setIntersectionUser(iop);
                        rl.setBdUser(rl.getGroupSize());
                        rl.setIopUser(iop);
                        rl.setTotalFailure(s.getFail());
                        rl.setBlackUser(s.getDtBlack());
                        rl.setRepetitionUser(0);
                        rl.setErrSend(s.getSendSitivity() + s.getSpeedOverLoad() + s.getMonthlyOverLoad());
                        rl.setFailSend(0);
                        rl.setIsResultBack(1);
                        smsOperationMapper.updateById(rl);
                    });
                });
            }
        });
        log.info("定时任务结束：smsResultTask");
    }

    /**
     * 短信日报分页条件查询
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject report(Map<String, Object> params) {
        ResultObject<Page<HashMap<String, Object>>> res = new ResultObject<>();
        // 总数
        int total = smsOperationMapper.countReportQuery(params);
        // 分页查询结果集
        List<HashMap<String, Object>> datas = smsOperationMapper.queryReportMap(params);
        // 分页
        Page<HashMap<String, Object>> page = new Page<>();
        page.setTotal(total);
        page.setData(datas);
        res.setData(page);
        return res;
    }

    /**
     * 短信日报导出
     *
     * @param params
     * @return
     */
    @Override
    public List<SMSDailyReportExportVo> dailyExportMap(Map<String, Object> params) {
        List<SMSDailyReportExportVo> datas = smsOperationMapper.dailyExportMap(params);
        return datas;
    }

    private SmsResponse remotePost(String strategyId,String qryDate){
        String taskNo = accessCode + strategyId;
        SmsRequest sr = new SmsRequest();
        sr.setTaskNo(taskNo);
        sr.setQueryTime(qryDate + "000000");
        Map<String, String> header = new HashMap<>(2);
        header.put("Content-Type", "application/json");
        header.put("charset", "utf-8");
        String result;
        try {
            result = HttpUtils.doPost(resultUrl, JSON.toJSON(sr), header);
            if (result != null) {
                log.info("短信效果统计返回:{}", result);
                JSONObject jo = JSON.parseObject(result);
                JSONObject data = jo.getJSONObject("resultData");
                if (data != null){
                    return JSON.toJavaObject(data, SmsResponse.class);
                }
            }
        } catch (Exception e) {
            log.error("调用短信效果统计接口失败", e);
            throw new MiguRuntimeException("调用短信效果统计接口失败", e);
        }
        return null;
    }
}
